package com.pinganfu.tesla.iwallet.util;

import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

import android.graphics.Bitmap;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.ChecksumException;
import com.google.zxing.DecodeHintType;
import com.google.zxing.EncodeHintType;
import com.google.zxing.FormatException;
import com.google.zxing.LuminanceSource;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;
import com.google.zxing.qrcode.QRCodeWriter;

public final class QrcodeUtil {

	private static final int QR_WIDTH = 120;
	private static final int QR_HEIGHT = 120;

	// 生成QR图
	public static Bitmap createImage(String qrText) {
		return createImage(qrText, QR_WIDTH, QR_HEIGHT);
	}

	// 生成QR图
	public static Bitmap createImage(String qrText, int qrWidth, int qrHeight) {
		Bitmap bitmap = null;
		try {
			// 需要引入core包
			QRCodeWriter writer = new QRCodeWriter();

			String text = qrText;
			LogUtil.i("生成的文本：" + text);

			// 把输入的文本转为二维码
			BitMatrix martix = writer.encode(text, BarcodeFormat.QR_CODE, qrWidth, qrHeight);

			LogUtil.i("w:" + martix.getWidth() + ", h:" + martix.getHeight());

			Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
			hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
			BitMatrix bitMatrix = new QRCodeWriter().encode(text, BarcodeFormat.QR_CODE, qrWidth, qrHeight, hints);
			int[] pixels = new int[qrWidth * qrHeight];
			for (int y = 0; y < qrHeight; y++) {
				for (int x = 0; x < qrWidth; x++) {
					if (bitMatrix.get(x, y)) {
						pixels[y * qrWidth + x] = 0xff000000;
					} else {
						pixels[y * qrWidth + x] = 0xffffffff;
					}

				}
			}

			bitmap = Bitmap.createBitmap(qrWidth, qrHeight, Bitmap.Config.ARGB_8888);
			bitmap.setPixels(pixels, 0, qrWidth, 0, 0, qrWidth, qrHeight);

		} catch (WriterException e) {
			e.printStackTrace();
		}
		return bitmap;
	}

	// 解析QR图片
	public static String scanningImage(Bitmap bitmap) {

		Map<DecodeHintType, String> hints = new HashMap<DecodeHintType, String>();
		hints.put(DecodeHintType.CHARACTER_SET, "utf-8");

		// 获得待解析的图片
		LuminanceSource source = new RGBLuminanceSource(bitmap);
		BinaryBitmap bitmap1 = new BinaryBitmap(new HybridBinarizer(source));
		QRCodeReader reader = new QRCodeReader();
		Result result;
		try {
			result = reader.decode(bitmap1, hints);
			return result.getText();

		} catch (ChecksumException e) {
			e.printStackTrace();
		} catch (NotFoundException e) {
			e.printStackTrace();
		} catch (FormatException e) {
			e.printStackTrace();
		}
		return null;
	}
}
